<?php

class agentCard {

	private $db = null;
	
    public function __construct($conn) {
    	$this->db = $conn;
    }
    
    public function __destruct(){
    	unset($this->db);
    }
    
    public function applyCard($param_uin,$param_cardValue,$param_cardCount,$param_type){
    	if ($param_uin > 0 && $param_cardValue > 0 && $param_cardCount > 0 && $param_type){
    		$sql = 'CALL '.DB_NAME_KCARD.'.sp_applyCard('.$param_uin.','.$param_cardValue.','.$param_cardCount.',"'.$param_type.'",true);';
    		$result = $this->executeSQL($sql);
    		if ($result == 1){
    			return 100;
    		}
    		elseif($result = 2){
    			return 101;
    		}
    		else{
    			return 102;
    		}
    	}
    	return false;
    }
    
	public function agentCardList($uin, $sortId, $tbl, $limit = 1, $id = 0) {
		if ($uin > 0) {
			$while .= ' WHERE uin = ' . $uin;
		}
		if ($id > 0) {
			$while .= ' AND id = ' . $id;
		}
		if ($sortId > 0){
			$while .= ' AND sortId = '.$sortId;
		}
		$sql = 'SELECT * FROM ' . DB_NAME_KCARD . '.'.$tbl . $while . ' ORDER BY status ASC,id DESC LIMIT ' . $limit;
		$result = $this->getAllSQL($sql);		
		if (is_array($result)) {
			$result['cnt'] = count($result);
			return $result;
		}
	}

	public function limit($uin,$sortId,$tbl) {
		if ($uin > 0) {
			$while .= ' WHERE uin = ' . $uin;
		}
		if ($sortId > 0){
			$while .= ' AND sortId = '.$sortId;
		}
		$sql = 'SELECT COUNT(id) AS total FROM ' . DB_NAME_KCARD . '.'.$tbl . $while;
		$result = $this->executeSQL($sql);
		if ($result > 0) {
			return $result;
		}
	}
	
	public function execInvalid($id,$uin,$type,$sortId = 0){
		if ($id > 0 && $uin > 0 && $type != ''){
			$sql = 'CALL '.DB_NAME_KCARD.'.sp_invalidCard("'.$id.'","'.$uin.'","'.$sortId.'","'.$type.'",true);';
			$result = $this->executeSQL($sql);
    		if ($result == 1){
    			return 100;
    		}
    		else{
    			return 101;
    		}
    	}
    	return false;
	}
    
    private function executeSQL($sql) {
		if ($sql != '') {
			$result = $this->db->Execute($sql);
			if (is_object($result)) {
				$arrRow = $result->FetchRow();
				$this->db->NextResult();
				return $arrRow[0];
			}
		}
		return false;
	}

	private function getAllSQL($sql) {
		if ($sql != '') {
			$result = $this->db->GetAll($sql);
			if (is_array($result)) {
				$this->db->NextResult();
				return $result;
			}
		}
		return false;
	}

	private function showPage($total, $perpage = 10) {
		if ($total > 0) {
			require_once ('page.class.php');
			$page = new extpage(array (
				'total' => $total,
				'perpage' => $perpage
			));
			$pageArr['page'] = $page->show();
			$pageArr['limit'] = $page->limit();
			unset ($page);
		}
		return $pageArr;
	}
}
?>